/**
 * 
 */
package org.braketester.model;

import java.io.IOException;

import org.braketester.entry.ExceptionResolver;
import org.braketester.entry.FramesThread;
import org.extdev.connection.Connection;
import org.extdev.connection.ltr.LTR212LibConnection;
import org.extdev.device.ltr.LTRCrate;
import org.extdev.libraries.ltr.LTRException;
import org.extdev.protocol.Protocol;

/**
 * @author LAP
 *
 */
public class LTR212DeviceSingletonCeeper {
	
	private LTR212ThreadRequestedDevice device;
	private LTR212DeviceSingletonCeeper() {
		tryCreateDevice();
	}
	
	private static class LTR212DeviceSingletonCeeperHolder {
		public static final LTR212DeviceSingletonCeeper INSTANCE = new LTR212DeviceSingletonCeeper();
	}
	
	public static synchronized LTR212DeviceSingletonCeeper getInstance() {
		return LTR212DeviceSingletonCeeperHolder.INSTANCE;
	}
	
	public LTR212ThreadRequestedDevice getDevice() {
		return device;
	}
	
	public void resetConnection(LTR212Preferences preferences) {
		if (device.getConnection().isConnected())
			tryDisconnect();
		device.setConnection(createConnection(preferences));
	}
	
	private void tryDisconnect() {
		try {
			device.getConnection().disconnect();
		} catch (Exception e) {
			ExceptionResolver.getInstance().logException(e);
			ExceptionResolver.getInstance().showException(e);
		}
	}
	
	private Connection createConnection(LTR212Preferences preferences) {
		Connection connection = null;
		try {
			if (preferences != null)
				connection = new LTR212LibConnection(
						preferences.getCrate(), 
						preferences.getModuleNo());
			else {
				connection = new LTR212LibConnection(LTRLoader.getInstance().getContainer().getCrates().getFirst());
			}
		} catch (LTRException e) {
			ExceptionResolver.getInstance().logException(e);
			ExceptionResolver.getInstance().showException(e);
			System.exit(e.getExceptionNumber());
		}
		return connection;
	}
	
	private Protocol tryCreateProtocol() {
		Protocol protocol = null;
		try {
			protocol = new LTR212ClearVoltageProtocol();
		} catch (SecurityException | IOException e) {
			ExceptionResolver.getInstance().logException(e);
			ExceptionResolver.getInstance().showException(e);
			System.exit(-1);
		}
		return protocol;
	}
	
	private void tryCreateDevice() {
		try {
			device = new LTR212ThreadRequestedDevice(
					createConnection(null),
					tryCreateProtocol());
		} catch (LTRException e) {
			ExceptionResolver.getInstance().logException(e);
			ExceptionResolver.getInstance().showException(e);
			System.exit(e.getExceptionNumber());
		}
	}
}
